<template>
  <el-dialog title="新建文件" :visible.sync="open" width="500px" append-to-body @closed="closed">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <el-form-item label="所在文件夹" prop="folderName">
        <el-input v-model="this.folderName" disabled />
      </el-form-item>
      <el-form-item label="文件名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入文件名称" />
      </el-form-item>
      <el-form-item label="文件" prop="file">
        <el-upload
          ref="uploadComp"
          class="upload-demo"
          :action="`${baseUrl}upload`"
          :on-success="uploadSuccess"
          :on-error="uploadError"
          :limit="1">
          <el-button :loading="loading" size="small" type="primary">点击上传</el-button>
          <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过2M</div> -->
        </el-upload>
      </el-form-item>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button type="primary" :loading="submitting" @click="submit">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>
<script>
import { uploadFile, addFile } from "@/api/folder"
export default {
  data() {
    return {
      open: false,
      loading: false,
      submitting: false,
      baseUrl: process.env.VUE_APP_BASE_API,
      folderName: "",
      form: {
        name: "",
        path: "",
        folderId: "",
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: "请输入文件夹名称", trigger: "blur" }
        ],
      }
    }
  },
  methods: {
    show(data) {
      this.open = true;
      this.form.name = "";
      this.form.folderId = data.id;
      this.folderName = data.name;
      this.form.path = "";
    },
    uploadSuccess(response, file, fileList) {
      if(response.status == "2000") {
        this.form.path = response.data.path
        this.form.fileSize = response.data.fileSize;
        this.form.fileType = response.data.fileType;
      } else {
        this.$message.error("文件上传失败");
      }
    },
    uploadError(err, file, fileList) {
      this.$message.error("文件上传失败");
    },
    submit() {
      if (!this.form.name || !this.form.path) {
        return this.$message.error("请输入文件名称");
      }
      this.submitting = true;
      addFile(this.form).then(res => {
        this.$modal.msgSuccess("添加成功");
        this.open = false;
        this.$emit("addSuccess")
      }).catch(() => {}).finally(() => {
        this.submitting = false
      });
    },
    cancel() {
      this.open = false;
    },
    closed() {
      this.folderName = "";
      this.$refs["uploadComp"].clearFiles();
    }
  }
}
</script>